package com.qijia.travel.app;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import com.qijia.travel.common.Constants;

public class ExcelImportor implements FileImport {

	private Map<String, String> getPropertyMap() throws AppErrorException {
		InputStream inputStream = this.getClass().getClassLoader()
				.getResourceAsStream(Constants.TOURIST_EXCEL_FILE_PRO);
		Properties p = new Properties();
		try {
			p.load(inputStream);
		} catch (IOException e1) {
			throw new AppErrorException("读取 TOURIST_EXCEL_FILE_PRO 配置文件出错!");
		}

		Map<String, String> propertyMap = new HashMap<String, String>();
		for (Object key : p.keySet()) {
			propertyMap.put((String) key, (String) p.get(key));
		}
		return propertyMap;
	}

	public List<Map<String, Object>> importData(String excelFile)
			throws AppErrorException {
		List<Map<String, Object>> resultList = new ArrayList<Map<String, Object>>();
		List<String> titleKey = new ArrayList<String>();
		Map<String, Object> dataMap = null;
		Map<String, Integer> titleMap = new HashMap<String, Integer>();
		Map<String, String> titleMapped = getPropertyMap();
		try {
			InputStream is = new FileInputStream(excelFile);
			HSSFWorkbook rwb = new HSSFWorkbook(is);
			HSSFSheet sheet = rwb.getSheetAt(0);
			HSSFRow titleRow = sheet.getRow(0);
			for (int j = titleRow.getFirstCellNum(); j < titleRow
					.getLastCellNum(); j++) {
				HSSFCell titleCell = titleRow.getCell(j);
				if (titleCell == null)
					continue;
				HSSFRichTextString cellValue = titleCell
						.getRichStringCellValue();
				if (cellValue == null)
					continue;
				String value = cellValue.toString().trim();
				titleKey.add(value);

				if (titleMapped.containsValue(value))
					titleMap.put(value, j);
			}
			int typeCode = -1;
			for (int i = sheet.getFirstRowNum() + 1; i <= sheet.getLastRowNum(); i++) {
				HSSFRow row = sheet.getRow(i);
				dataMap = new HashMap<String, Object>();
				for (String titleValue : titleMap.keySet()) {
					HSSFCell cell = null;
					try {
						if (row != null)
							cell = row.getCell(titleMap.get(titleValue));
						if (cell == null)
							continue;

						typeCode = cell.getCellType();
					} catch (Exception e) {
						throw new AppErrorException("获取Excel[title:"
								+ titleValue + ">>" + titleMap.get(titleValue)
								+ "]数据时发生错误", e);
					}

					Object obj = null;
					if (typeCode == HSSFCell.CELL_TYPE_NUMERIC) {
						if (HSSFDateUtil.isCellDateFormatted(cell)) {// 判断是否是日期
							SimpleDateFormat dateformat = new SimpleDateFormat(
									"yyyy-MM-dd");
							Date dt = HSSFDateUtil.getJavaDate(cell
									.getNumericCellValue());
							obj = dateformat.format(dt);
						} else
							obj = cell.getNumericCellValue();
					} else if (typeCode == HSSFCell.CELL_TYPE_STRING) {
						obj = cell.getRichStringCellValue().toString();
					} else if (typeCode == HSSFCell.CELL_TYPE_FORMULA) {
						obj = cell.getCellFormula();
					} else if (typeCode == HSSFCell.CELL_TYPE_BLANK) {
						// obj = cell.getBooleanCellValue();
					} else if (typeCode == HSSFCell.CELL_TYPE_FORMULA) {
						obj = cell.getBooleanCellValue();
					} else if (typeCode == HSSFCell.CELL_TYPE_ERROR) {
						obj = cell.getErrorCellValue();
					} else {
						System.out.println(titleValue + "--->" + typeCode
								+ "====");
					}

					if (obj == null)
						continue;

					for (String key : titleMapped.keySet()) {
						if (titleValue.equalsIgnoreCase(titleMapped.get(key))) {
							dataMap.put(key, obj);
						}
					}
				}
				if (!dataMap.isEmpty())
					resultList.add(dataMap);
			}
		} catch (FileNotFoundException e) {
			throw new AppErrorException("解析Excel时未能找到此文件[" + excelFile + "]", e);
		} catch (IOException e) {
			throw new AppErrorException("初始化POI组件时出现错误", e);
		}
		return resultList;
	}
}
